package com.kuaifawu.lwnlawyerclient.Activity;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.*;
import android.os.Process;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Lib.LWNJsonToData;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;


/**
 * A login screen that offers login via email/password.
 */
public class LWNLoginActivity extends Activity{

    // UI references.
    @ViewInject(R.id.login_phone)
    private AutoCompleteTextView atextView_phone;
    @ViewInject(R.id.login_password)
    private AutoCompleteTextView atextView_password;
    @ViewInject(R.id.login_in_button)
    private Button button_loginIn;
    @ViewInject(R.id.button_wangjimima)
    private Button button_wangjimima;
    @ViewInject(R.id.login_show)
    private ImageButton button_show;
    @ViewInject(R.id.login_join_button)
    private Button login_join_button;

    private Boolean bool_isShow = false;
    private LWNLoginActivity activity_self;
    private String joinurl="http://www.mikecrm.com/f.php?t=SMD5Fr";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ViewUtils.inject(this);
        activity_self = this;
        initView();
    }

    private void initView(){
        button_wangjimima.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("name", "findMM");
                intent.setClass(LWNLoginActivity.this, LWNFindMM.class);
                startActivity(intent);
            }
        });

        button_show.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(bool_isShow){
                    button_show.setImageDrawable(getResources().getDrawable(R.drawable.login_hidden));
                    atextView_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }else{
                    button_show.setImageDrawable(getResources().getDrawable(R.drawable.login_show));
                    atextView_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
                }
                bool_isShow =! bool_isShow;
            }
        });

        button_loginIn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
        login_join_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(LWNLoginActivity.this,LWNLogin_Join.class);
                Bundle bundle=new Bundle();
                bundle.putString("skipurl",joinurl);
                bundle.putBoolean("isjoin",true);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {

        // Reset errors.
        atextView_phone.setError(null);
        atextView_password.setError(null);

        // Store values at the time of the login attempt.
        String phone = atextView_phone.getText().toString();
        String password = atextView_password.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid email address.
        if (TextUtils.isEmpty(phone)) {
            atextView_phone.setError(getString(R.string.error_field_phone));
            focusView = atextView_phone;
            cancel = true;
        }else if(TextUtils.isEmpty(password)){
            atextView_password.setError(getString(R.string.error_field_password));
            focusView = atextView_password;
            cancel = true;
        }else if (!isPhoneValid(phone)){
            atextView_phone.setError(getString(R.string.error_invalid_phone));
            focusView = atextView_phone;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            LWNNetworkCenter center=LWNNetworkCenter.getInstance();
            if(center.checkNetworkState(this)){
                getLoginFromNetwork(phone, password);
            }else{
                ToastView_custom toast = new ToastView_custom(this);
                toast.showCustom(this,  "请连接网络");
            }

        }
    }

    /**
     * @param @检测手机
     * @return BOOL
     */
    private boolean isPhoneValid(String phone){
        /**
         * 验证手机格式
		移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
		联通：130、131、132、152、155、156、185、186
		电信：133、153、180、189、（1349卫通）
		总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
		*/
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "[1][358]\\d{9}";
        if (TextUtils.isEmpty(phone)) {
            return false;
        }
        else {
            return phone.matches(telRegex);
        }
    }

    /**
     * 登陆网络请求
     */
    public void getLoginFromNetwork(String string_phone, String string_password) {
        final ProgressDialog proDialog = android.app.ProgressDialog.show(this, "", "登录中，请稍候...");
        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        String string_url = center.getInstance().getLogin(string_phone, string_password, activity_self);
        //System.out.println(string_url);
        HttpUtils http = center.getUtils();
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        proDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg  = jsonObject.getString("msg");
                            switch (Integer.parseInt(string_code)){
                                case 10000: {
                                    String string_token = jsonObject.getString("token");
                                    String string_uid   = jsonObject.getString("id");

                                    LWNJsonToData.saveLawyerInfoWithJsonString(jsonObject.getJSONObject("lawyerInfo"));

                                    LWNModel_user.getInstance().setString_token(activity_self,string_token);
                                    LWNModel_user.getInstance().setString_uid(activity_self,string_uid);



                                    ToastView_custom toast = new ToastView_custom(activity_self);
                                    toast.showCustom(activity_self, string_msg);


                                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                    if (imm.isActive()) {
                                        //如果开启
                                        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
                                        //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
                                    }

                                    TimerTask task = new TimerTask() {
                                        public void run() {
                                            finish();
                                        }
                                    };
                                    Timer timer = new Timer();
                                                                                                                               timer.schedule(task, 2 * 1000);
                                }
                                Intent intent=null;

                                intent=new Intent(LWNLoginActivity.this,MainActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putBoolean("isNewLogin",true);
                                    intent.putExtras(bundle);
                                startActivity(intent);
                                    finish();
                                break;
                                case 10001: {//登陆失败
                                    Toast toast = Toast.makeText(getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                                case 10003: {//手机号不存在
                                    Toast toast = Toast.makeText(getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();

                                }
                                break;
                                default: {
                                    Toast toast = Toast.makeText(getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }
    private long firsttime=0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        if(System.currentTimeMillis()-firsttime>500){
            firsttime = System.currentTimeMillis();
            ToastView_custom toast = new ToastView_custom(activity_self.getApplicationContext());
            toast.showCustom(activity_self, "再按一次退出程序");

        }else{
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//            home.addCategory(Intent.CATEGORY_HOME);
//
//            startActivity(home);
            finish();
        }
        return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}



